package com.vehicle.repair.service;

import com.vehicle.repair.model.User;
import com.vehicle.repair.model.Vehicle;
import com.vehicle.repair.repository.VehicleRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Optional;

@Service
@Transactional
public class VehicleService {
    private final VehicleRepository vehicleRepository;
    private final UserService userService;

    public VehicleService(VehicleRepository vehicleRepository, UserService userService) {
        this.vehicleRepository = vehicleRepository;
        this.userService = userService;
    }

    public Vehicle createVehicle(Vehicle vehicle, Integer ownerId) {
        User owner = userService.getUserById(ownerId)
                .orElseThrow(() -> new IllegalArgumentException("Owner not found"));
        
        if (vehicleRepository.existsByPlateNumber(vehicle.getPlateNumber())) {
            throw new IllegalArgumentException("Plate number already exists");
        }
        
        vehicle.setOwner(owner);
        return vehicleRepository.save(vehicle);
    }

    public Optional<Vehicle> getVehicleById(Integer id) {
        return vehicleRepository.findById(id);
    }

    public Optional<Vehicle> getVehicleByPlateNumber(String plateNumber) {
        return vehicleRepository.findByPlateNumber(plateNumber);
    }

    public List<Vehicle> getVehiclesByOwner(Integer ownerId) {
        User owner = userService.getUserById(ownerId)
                .orElseThrow(() -> new IllegalArgumentException("Owner not found"));
        return vehicleRepository.findByOwner(owner);
    }

    public Vehicle updateVehicle(Vehicle vehicle) {
        return vehicleRepository.save(vehicle);
    }

    public void deleteVehicle(Integer id) {
        vehicleRepository.deleteById(id);
    }
}
